package P042_UtilClassNoInstantiation;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 让工具类不可实例化
 * @author xufy1
 */
public class UtilClassNoInstantiation {

    @Test
    public void test1(){
        //通过类名调用 static静态方法
        System.out.println(Math.abs(-1));
        // 不允许使用new实例调用方法
        int i = MathUtil.MathUtilTest();
        System.out.println("  "+i);
    }

    @Test
    public void test2() throws Exception {

        Class<?> aClass = Class.forName("P042_UtilClassNoInstantiation.MathUtil");
        //private MathUtil() 私有构造方法，访问报错
//        Object obj = aClass.newInstance();

        //利用反射，通过构造方法生成实例
        Constructor<?> constructor = aClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        Object obj = constructor.newInstance();

        MathUtil mathUtil= (MathUtil) obj;
        System.out.println("打印 address值:    "+mathUtil.address);

    }
    @Test
    public void test3() throws Exception{

        Class<?> bClass = Class.forName("P042_UtilClassNoInstantiation.MathUtilInvoke");

        //获取公共方法 MathUtilTest()
        Method bMathUtilTest = bClass.getMethod("MathUtilTest");
        bMathUtilTest.invoke(bClass);


        //通过构造方法生成实例
        Constructor<?> constructor = bClass.getDeclaredConstructor();
        constructor.setAccessible(true);
        Object obj = constructor.newInstance();

        Field name=bClass.getDeclaredField("name");
        name.setAccessible(true);
        System.out.println(name.get(obj));
        name.set(obj, "che");
        System.out.println(name.get(obj));
    }
}
